package com.cloudkinto.service.system.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudkinto.bo.system.LoginLogQueryBo;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.dao.LoginLogDao;
import com.cloudkinto.entity.LoginLogDo;
import com.cloudkinto.service.system.LoginLogService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * <p>
 * 登录日志 service实现类
 * </p>
 *
 * @author hua
 * @since 2025-01-13
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class LoginLogServiceImpl extends ServiceImpl<LoginLogDao, LoginLogDo> implements LoginLogService {
    @Override
    public PageResult getListPage(LoginLogQueryBo bo) {
        IPage<LoginLogDo> page = new Page<>(bo.getCurrent(), bo.getPageSize());
        page = this.page(page, this.queryBuild(bo));
        return new PageResult(page.getRecords(), (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
    }

    private LambdaQueryWrapper<LoginLogDo> queryBuild(LoginLogQueryBo bo) {
        LambdaQueryWrapper<LoginLogDo> lqw = new LambdaQueryWrapper<>();
        lqw.eq(LoginLogDo::getTenantId, bo.getTenantId());
        lqw.eq(LoginLogDo::getCompanyId, bo.getCompanyId());
        lqw.eq(StrUtil.isNotBlank(bo.getSource()), LoginLogDo::getSource, bo.getSource());
        lqw.ge(Objects.nonNull(bo.getStartDate()), LoginLogDo::getLoginTime, bo.getStartDate());
        lqw.le(Objects.nonNull(bo.getEndDate()), LoginLogDo::getLoginTime, bo.getEndDate());
        lqw.likeRight(StrUtil.isNotBlank(bo.getLoginUsername()), LoginLogDo::getLoginUsername, bo.getLoginUsername());
        lqw.orderByDesc(LoginLogDo::getId);
        return lqw;
    }


}
